package itsm.isperp.module.controller.task;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IBean;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.project.ProjectDomain;
import itsm.isperp.module.dto.project.ProjectDomain.ProjectDomainType;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.entity.task.TskInspectTemplateDef;
import itsm.isperp.module.entity.task.TskPlanTask;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.task.TskInspectTemplateDefService;
import itsm.isperp.module.service.task.TskPlanTaskService;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("task/planTask")
public class TskPlanTaskController extends BaseController<TskPlanTask> {

	/**
	 * 
	 */
	@Autowired
	protected TskPlanTaskService tskPlanTaskService;

	@Autowired
	protected ProjProjectService projProjectService;

	@Autowired
	protected AppDictService appDictService;

	@Override
	public TskPlanTaskService getService() {
		return tskPlanTaskService;
	}

	@Override
	public String getPageTitle() {
		return "计划任务";
	}

	/**
	 * 计划任务编辑界面
	 * 
	 * @return 计划任务编辑界面视图
	 */
	@RequestMapping("edit")
	@Override
	public ModelAndView edit(String id, HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		TskPlanTask tskPlanTask = null;

		List<AppDict> task_execute_Type = appDictService
				.findByType("TASK_EXECUTE_TYPE");
		mv.addObject("task_execute_Type", task_execute_Type);

		String projectId = req.getParameter("projectId");
		List<ProjProject> projects = null;
		if (StringUtils.isEmpty(projectId)) {
			mv.addObject("projects",
					projProjectService.findAllPublished("id", "name"));
		} else {
			JqGridRequest projectRequest = new JqGridRequest();
			projectRequest.setSelectColumns("id", "name", "start_date",
					"end_date");
			projectRequest.isQueryOne(true);
			projectRequest
					.addFilterRule("id", JqGridFilterRuleOp.eq, projectId);

			projects = projProjectService.findAll(projectRequest);
			mv.addObject("projects", projects);

		}

		if (StringUtils.isEmpty(id)) {

			tskPlanTask = new TskPlanTask();
			tskPlanTask.setId(HibernateUUIDGenerator.generate());
			if (task_execute_Type.size() > 0)
				tskPlanTask.setExcuteType(task_execute_Type.get(0).getCode());

			tskPlanTask.setReleaseBeforeDays(1);

			if (projects != null && projects.size() == 1) {

				Date sdate = projects.get(0).getStartDate();
				// Date edate = projects.get(0).getEndDate();

				tskPlanTask.setExcutePeriodStart(sdate);

				// tskPlanTask.setExcutePeriodEnd(edate);

			}

		} else {
			tskPlanTask = this.getService().findOne(id);

			TskInspectTemplateDefService tskInspectTemplateDefService = ContextHolder
					.getSpringBean("tskInspectTemplateDefService");

			TskInspectTemplateDef def = tskInspectTemplateDefService
					.findOne(tskPlanTask.getInspectTemplateDefId());
			if (def != null)
				mv.addObject("inspectTemplateDefName", def.getName());

		}
		mv.addObject("model", tskPlanTask);

		if (!StringUtils.isEmpty(tskPlanTask.getExcuteWeekDays())) {
			tskPlanTask.setSelectedWeekDays(tskPlanTask.getExcuteWeekDays()
					.split(","));
		}
		if (!StringUtils.isEmpty(tskPlanTask.getExcuteMonthDays())) {
			tskPlanTask.setSelectedMonthDays(tskPlanTask.getExcuteMonthDays()
					.split(","));
		}

		// 项目阶段
		mv.addObject("project_stage",
				appDictService.findByType("PROJECT_STAGE"));
		// 任务重要程度
		mv.addObject("task_prioirty",
				appDictService.findByType("TASK_PRIORITY"));
		// 任务执行类别

		// 星期-天数设置
		mv.addObject("excute_WeekDays", appDictService.findByType("WEEK_DAYS"));

		// 月-天数设置
		mv.addObject("excute_MonthDays",
				appDictService.findByType("MONTH_DAYS"));

		return mv;
	}

	@RequestMapping(value = { "manage", "" })
	@Override
	public ModelAndView manage(HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();

		mv.addObject(
				"projects",
				projProjectService.findAll(
						new JqGridRequest().isPageable(false).setSelectColumns(
								"id", "name")).getContent());

		return mv;
	}

	@RequestMapping("list")
	@ResponseBody
	@Override
	public PageResponse<TskPlanTask> list(JqGridRequest request,
			HttpServletRequest req) {

		String projectId = req.getParameter("projectId");
		if (StringUtils.isNotEmpty(projectId)) {
			request.addFilterRule("project_id", JqGridFilterRuleOp.eq,
					projectId);
		}

		return this.getService().findAll(request).toPage();

	}

	/**
	 * 保存实体
	 * 
	 * @param model
	 *            　一个继承与IBean接口的实体　{@link IBean}
	 * @return json结果数据
	 */
	@RequestMapping("save")
	@ResponseBody
	@Override
	public ResultMessage save(TskPlanTask model, HttpServletRequest req) {

		model.setExcuteWeekDays(getSelectedValue(model.getSelectedWeekDays()));

		model.setExcuteMonthDays(getSelectedValue(model.getSelectedMonthDays()));

		this.getService().saveOrUpdate(model);
		return ResultMessage.newInstance(true);

	}

	private String getSelectedValue(String[] selectValues) {

		String tmp = "";
		if (selectValues == null)
			return tmp;
		for (int i = 0; i < selectValues.length; i++) {
			if (i != selectValues.length - 1) {
				tmp = tmp + selectValues[i] + ",";
			} else {
				tmp = tmp + selectValues[i];
			}
		}
		return tmp;
	}

}
